//
//  JoLoopView.swift
//  soapp
//
//  Created by zhu xietong on 2018/2/17.
//

import Foundation
//
//  EeLoopView.swift
//  housingResources
//
//  Created by zhu xietong on 2017/7/25.
//  Copyright © 2017年 节操君. All rights reserved.
//

import UIKit
import Eelay
import AsyncDisplayKit


//#define dotW 22 // 圆点宽
//#define dotH 7  // 圆点高
//#define magrin 8    // 圆点间距




open class EePageControl: UIPageControl {
    public static var pointWidth:CGFloat = 7
    public static var pointHeight:CGFloat = 7
    public static var margin:CGFloat = 10
    
    
    
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        let marginX:CGFloat = EePageControl.pointWidth + EePageControl.margin
        let newWidth:CGFloat = (self.subviews.count - 1).cg_floatValue * marginX
        self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: newWidth, height: frame.size.height)
        var center:CGPoint = self.center
        center.x = superview?.center.x ?? 0
        self.center = center
        
        var i = 0
        for one in self.subviews {
            one.frame = CGRect(x: i.cg_floatValue * marginX, y: one.frame.origin.y, width: EePageControl.pointWidth, height: EePageControl.pointHeight)
            i = i + 1
        }
        
        
//            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, newW, self.frame.size.height);
//
//        //设置居中
//        CGPoint center = self.center;
//        center.x = self.superview.center.x;
//        self.center = center;
//
//        //遍历subview,设置圆点frame
//        for (int i=0; i<[self.subviews count]; i++) {
//            UIImageView* dot = [self.subviews objectAtIndex:i];
//
//            if (i == self.currentPage) {
//                [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y - 1, dotW_Active, dotW_Active)];
//            }else {
//                [dot setFrame:CGRectMake(i * marginX, dot.frame.origin.y, dotW, dotW)];
//            }
//        }


    }
}


public enum HorizontalAlignment{
    case left(UIOffset)
    case right(UIOffset)
    case center(UIOffset)
    case none
}

class JoPageControl: JoView {
//    let pageControl = EePageControl()
    let pageControl = UIPageControl()
    var alignment:HorizontalAlignment = .center(.zero)
    
    init(alignment:HorizontalAlignment) {
        super.init()
        self.alignment = alignment
        layControll()
    }
    
    required public init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required public init() {
        super.init()
    }
    
    public required init?(coder aDecoder: NSCoder) {
        super.init()
    }
    
    func layControll() {
        pageControl.currentPage = 0;
        pageControl.currentPageIndicatorTintColor = UIColor.main_color
        pageControl.pageIndicatorTintColor = UIColor(shex: "#ccc")
        
        switch alignment {
        case .left:
            eelay = [
                [pageControl,[ee.L.Y,[10,0]]]
            ]
        case .right:
            eelay = [
                [pageControl,[ee.R.Y,[-10,0]]]
            ]
        case .center(let offset):
            
            eelay = [
                [pageControl,[ee.X.Y,[offset.horizontal,offset.vertical]]]
            ]
        case .none:
            break
        }
    }
    override var intrinsicContentSize: CGSize{
        return [30,Swidth]
    }
}

//class ScrollNode: ASScrollNode {
//    var nodes:[ASDisplayNode] = [ASDisplayNode]()
//    override func layoutThatFits(_ constrainedSize: ASSizeRange) -> ASLayout {
//        let spec = ASStackLayoutSpec(direction: <#T##ASStackLayoutDirection#>, spacing: <#T##CGFloat#>, justifyContent: <#T##ASStackLayoutJustifyContent#>, alignItems: <#T##ASStackLayoutAlignItems#>, children: <#T##[ASLayoutElement]#>)
//    }
//}


public class JoLoopView<T:MoDisplayNode>: MoDisplayNode,UIScrollViewDelegate,EeActionDelegate {
    public func active(onwer: Any, actionID: String, data: NSMutableDictionary) {
        imgClick()
    }
    
    public var alignment:HorizontalAlignment = .center(.zero)
    var kitSize = CGSize.zero
    
    public init(_ pageControlAlign:HorizontalAlignment,size:CGSize) {
        super.init()
        self.kitSize = size
        self.alignment = pageControlAlign
        addLayoutRules()
    }
    
 
    public required init() {
        super.init()
    }
    
    public let scrollNode = ASScrollNode()
    
    public var scrollView:UIScrollView{
        get{
            return scrollNode.view
        }
    }
    
    public var pageControlHeight = 30
    
    
    var pageNode = ASDisplayNode()
    public var pageControl:UIPageControl{
        get{
            if let pageC = self.pageNode.view as? JoPageControl
            {
                return pageC.pageControl
            }
            return UIPageControl()
        }
    }
    
    public var imgIndexOf = 0
    public var timer:SwiftTimer?
    public weak var deletate:EeActionDelegate?
    
    public var selectAction:(Int,NSMutableDictionary) ->Void = {_,_  in}
    
    public var oldContentOffsetX:CGFloat = 0.0
    public var interval:TimeInterval = 5
    
    typealias ContentView = T
    
    public var datas:NSMutableArray?{
        didSet{
            
            if let us = datas
            {
                let list = NSMutableArray()
                us.list{ (one:NSMutableDictionary, i) in
                    list.add(one)
                }
                
                if us.count > 1
                {
                    list.add(us.firstObject!)
                }
                self.listCount = list.count
                self.load(list: list)
            }
            else
            {
                self.listCount = 0
                self.load(list:  NSMutableArray())
            }
        }
    }
    
    public var page:Int{
        get{
            return self.pageControl.currentPage
        }
        set{
            self.pageControl.currentPage = newValue
            scrollView.setContentOffset([(self.pageControl.currentPage.cg_floatValue)*self.frame.width, 0], animated: false)
        }
    }
    
    var listCount:Int = 0
    
    let stack = ASStackLayoutSpec.horizontal()
    
    override public func addLayoutRules() {
        weak var wself = self
        
        self.pageNode = ASDisplayNode { () -> UIView in
            
            
            let algin = wself?.alignment ?? HorizontalAlignment.center(.zero)
            
            let pageControl = JoPageControl(alignment: algin)
            
            pageControl.pageControl.currentPage = 0;
            pageControl.pageControl.currentPageIndicatorTintColor = UIColor.main_color
            pageControl.pageControl.pageIndicatorTintColor = UIColor(shex: "#ccc")
            
            
            return pageControl
        }
        
        scrollNode.automaticallyManagesSubnodes = true
        scrollNode.automaticallyManagesContentSize = true
        scrollNode.scrollableDirections = .left
        scrollNode.clipsToBounds = false
        scrollNode.layoutSpecBlock = { node, constrainedSize in
            
            let vs = wself?.nodes ?? [ASLayoutElement]()
            let st = ASStackLayoutSpec(direction: .horizontal, spacing: 0, justifyContent: .start, alignItems: .stretch, children: vs)
            return st
        }
        //        let tap = UITapGestureRecognizer(target: self, action: #selector(imgClick))
        
        
        scrollNode.onDidLoad { (node) in
            
            let scrollV = node.view as? UIScrollView
            //            scrollV?.contentOffset = [0, 0]
            scrollV?.showsHorizontalScrollIndicator = false
            scrollV?.showsVerticalScrollIndicator = false
            scrollV?.isPagingEnabled = true
            scrollV?.delegate = wself;
            
        }
        
        
        
        self.imgIndexOf = 1;
        
//        mf.spec = .over([], over: .stack(["v",_justfy(.flex_end)], childs: [
//            pageNode["30"]
//            ]), back: scrollNode.Spec)
        
        pageNode.backgroundColor = .clear
   
    }
    
    public override func layoutDidFinish() {
        super.layoutDidFinish()
        scrollView.clipsToBounds = false
    }
    
    public var nodes:[T] = [T]()
    
    public override func specGetter() -> _Spec {
        var h = pageControlHeight
        switch self.alignment {
        case .none:
            h = 0
        default:
            break
        }
        return .over([], over: .stack(["v",_justfy(.flex_end)], childs: [
            pageNode["\(h)"]
            ]), back: scrollNode.Spec)
        
    }
    
    func updatePage(index:Int) {
        let oldP = pageControl.currentPage
        let newP = index
        if oldP != newP
        {
            pageControl.currentPage = newP
            if let list = datas
            {
                if list.count > index
                {
                    if let obj = list[newP] as? NSMutableDictionary
                    {
                        self.deletate?.active(onwer: self, actionID: "scrollTo[\(index)]", data: obj)
                    }
                }
            }
        }
    }
    
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let _ = self.datas
        {
            let point = scrollView.contentOffset
            let isRight = oldContentOffsetX < point.x
            oldContentOffsetX = point.x
            
            if (point.x > self.frame.width*(self.listCount.cg_floatValue-2)+self.frame.width*0.5) && (self.timer == nil)
            {
                updatePage(index: 0)
            }
            else if (point.x > self.frame.width*(self.listCount.cg_floatValue-2))&&(self.timer != nil)&&isRight{
                updatePage(index: 0)
            }
            else{
                let newP = Int((point.x + self.frame.width*0.5) / self.frame.width)
                updatePage(index: newP)
            }
            if (point.x >= self.frame.width*(self.listCount.cg_floatValue-1)) {
                scrollView.setContentOffset([self.frame.width+point.x-self.frame.width*self.listCount.cg_floatValue, 0], animated: false)
                
            }else if (point.x < 0) {
                scrollView.setContentOffset([point.x+self.frame.width*(self.listCount.cg_floatValue-1), 0], animated: false)
            }
        }
    }
    
    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        stopTimer()
    }
    
    public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        startTimer()
    }
    
    func startTimer() {
        weak var wself = self
        self.timer = SwiftTimer(interval: .seconds(Int(interval)), repeats: true, queue: .main, handler: { (timer) in
            wself?.nextPage()
        })
//            self.timer = Timer(timeInterval: interval, repeats: true) { (timer) in
//                wself?.nextPage()
//            }
//            RunLoop.current.add(self.timer!, forMode: RunLoopMode.commonModes)
 
        timer?.start()
    }
    
    
    func stopTimer() {
//        timer.cancel()
//        self.timer?.invalidate()
//        self.timer = nil
    }
    
    @objc func nextPage() {
        if listCount > 1
        {
            scrollView.setContentOffset([(self.pageControl.currentPage.cg_floatValue+1)*self.frame.width, 0], animated: true)
        }
    }
    
    func load(list:NSMutableArray){
        
        nodes.removeAll()
        
        
        for one in list
        {
            let imageView = T()
            imageView.mo.controller = self.mo.controller
            imageView.delegate = self
            if let dict = one as? NSMutableDictionary{
                imageView.mo.model = dict
            }
            imageView.style.width = ASDimension(unit: .points, value: kitSize.width)
            imageView.style.height = ASDimension(unit: .points, value: kitSize.height)
//            scrollNode.addSubnode(imageView)
            nodes.append(imageView)
        }
        
//        stack.children = self.nodes
        self.setNeedsLayout()
        self.pageControl.numberOfPages = listCount - 1;
        stopTimer()
        startTimer()
        self.clipsToBounds = false
        view.clipsToBounds = false
    }
    
    
    
    @objc func imgClick() {
        
        
        let index = pageControl.currentPage
        if let list = datas
        {
            if list.count > index
            {
                if let obj = list[index] as? NSMutableDictionary
                {
//                    print("-88888888--s-s-s|\(obj)===\(self.delegate)")
                    self.deletate?.active(onwer: self, actionID: "tap[\(index)]", data: obj)
                }
            }
        }
    }
    
    
    deinit {
        stopTimer()
    }
    
    
}

